package com.webmining.sherlock.service;

import com.webmining.sherlock.dao.UserDao;
import com.webmining.sherlock.dao.UserDaoForMap;
import com.webmining.sherlock.util.DataEncryptor;
import com.webmining.sherlock.util.DataValidator;
import com.webmining.sherlock.util.FieldsValidator;
import org.json.simple.JSONObject;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class RegistrationService {

    private static UserDao userDao = UserDaoForMap.getInstance();

    public static void doRegistration(HttpServletRequest request, HttpServletResponse response, ServletContext context) throws ServletException, IOException {
        PrintWriter responseWriter = response.getWriter();
        JSONObject jsonObject = new JSONObject();
        if (hasEmptyRequiredFields(request, jsonObject)) {
            responseWriter.print(jsonObject);
            return;
        }
        if (!DataValidator.isValidRegistrationData(request, jsonObject)) {
            responseWriter.print(jsonObject);
            return;
        } else {
            String email = request.getParameter("email");
            String password = request.getParameter("password");
            String encryptedPassword = DataEncryptor.encrypt(password);
            userDao.addUser(email, encryptedPassword);
            jsonObject.put("successfulRegistration", true);
        }
        responseWriter.print(jsonObject);
    }

    private static boolean hasEmptyRequiredFields(HttpServletRequest request, JSONObject response) {

        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String password_confirm = request.getParameter("confirmPassword");

        if (FieldsValidator.isEmptyField(email)) {
            response.put("loginFieldAttribute", FieldsValidator.EMPTY_FIELD_ERROR_MESSAGE);
            return true;
        }

        if (!FieldsValidator.isEmptyField(email)            &&
             (FieldsValidator.isEmptyField(password)         ||
              FieldsValidator.isEmptyField(password_confirm))
           ){
            response.put("passwordFieldAttribute", FieldsValidator.EMPTY_FIELD_ERROR_MESSAGE);
            response.put("confirmPasswordFieldAttribute", FieldsValidator.EMPTY_FIELD_ERROR_MESSAGE);
            return true;
        }

        return false;
    }

}
